package com.mayikt.weixin.service.impl;

import com.mayikt.utils.RedisLockUtils;

import java.util.UUID;

/**
 * @Classname ThreadRedis 测试redis锁
 * @Description SpringBoot SpringCloud 构建微服务电商平台。
 * @Created by CHEN JIN LONG
 * @Date 2019/1/22 23:29
 * @Version 1.0
 */
public class ThreadRedis implements Runnable {

    private RedisLockUtils redisLockUtils;

    public ThreadRedis(RedisLockUtils redisLockUtils) {
        this.redisLockUtils = redisLockUtils;
    }

    private static final int TIMEOUT = 10 * 1000;//超时时间 10s
    private static final String LOCK_KEY_VALUE = "LOCK";

    @Override
    public void run() {
        //加锁
        long time = System.currentTimeMillis() + TIMEOUT;
        String value = UUID.randomUUID().toString();
        if (!redisLockUtils.lock(LOCK_KEY_VALUE, value)) {
            System.out.println("【" + Thread.currentThread().getId() + "】获取锁失败，时间超时...");
            return;
        }
        System.out.println("【" + Thread.currentThread().getId() + "】获取锁成功...");
        //解锁
        redisLockUtils.unlock(LOCK_KEY_VALUE, value);
        System.out.println("【" + Thread.currentThread().getId() + "】释放锁成功...");
    }
}
